<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第20篇：文件操作, 张亚飞,飞凡空间,国学,Python,Go">
    <meta name="description" content="学习目标：掌握Python中文件打开、关闭、读取和写入的具体操作方法
实际开发中常常会遇到对数据进行持久化的场景，所谓持久化是指将数据从无法长久保存数据的存储介质（通常是内存）转移到可以长久保存数据的存储介质（通常是硬盘）中。实现数据持久化">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-w2ezfaoXE0" />
    <title>第20篇：文件操作 | 飞凡空间</title>
    <link rel="icon" type="image/png" href="/medias/my-logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="飞凡空间" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/my-logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">飞凡空间</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/my-logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">飞凡空间</div>
        <div class="logo-desc">
            
            诚者，天之道也；诚之者，人之道也。诚者，不勉而中，不思而得。从容中道，圣人也；诚之者，择善而固执者也。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/%E7%AC%AC20%E7%AF%87.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第20篇：文件操作
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                                <span class="chip bg-color">Python之路</span>
                            </a>
                        
                            <a href="/tags/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/">
                                <span class="chip bg-color">文件操作</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Python/" class="post-category">
                                Python
                            </a>
                        
                            <a href="/categories/Python/base/" class="post-category">
                                base
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-12-21
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    34 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>学习目标</strong>：掌握Python中文件打开、关闭、读取和写入的具体操作方法</p>
<p>实际开发中常常会遇到对数据进行持久化的场景，所谓持久化是指将数据从无法长久保存数据的存储介质（通常是内存）转移到可以长久保存数据的存储介质（通常是硬盘）中。实现数据持久化最直接简单的方式就是通过<strong>文件系统</strong>将数据保存到<strong>文件</strong>中。</p>
<p>计算机的<strong>文件系统</strong>是一种存储和组织计算机数据的方法，它使得对数据的访问和查找变得容易，文件系统使用<strong>文件</strong>和<strong>树形目录</strong>的抽象逻辑概念代替了硬盘、光盘、闪存等物理设备的数据块概念，用户使用文件系统来保存数据时，不必关心数据实际保存在硬盘的哪个数据块上，只需要记住这个文件的路径和文件名。在写入新数据之前，用户不必关心硬盘上的哪个数据块没有被使用，硬盘上的存储空间管理（分配和释放）功能由文件系统自动完成，用户只需要记住数据被写入到了哪个文件中。</p>
<p>在学习文件操作之前，先来回顾一下编码的相关以及先关数据类型的知识。</p>
<ul>
<li><p>字符串类型（<code>str</code>），在程序中用于表示文字信息，本质上是<code>unicode</code>编码中的二进制。</p>
<pre class="line-numbers language-python"><code class="language-python">name <span class="token operator">=</span> <span class="token string">"张亚飞"</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</li>
<li><p>字节类型（bytes）</p>
<ul>
<li><p>可表示文字信息，本质上是utf-8/gbk等编码的二进制（对unicode进行压缩，方便文件存储和网络传输。）</p>
<pre class="line-numbers language-python"><code class="language-python">name <span class="token operator">=</span> <span class="token string">"张亚飞"</span>
data <span class="token operator">=</span> name<span class="token punctuation">.</span>encode<span class="token punctuation">(</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># b'\xe6\xad\xa6\xe6\xb2\x9b\xe9\xbd\x90'</span>

result <span class="token operator">=</span> data<span class="token punctuation">.</span>decode<span class="token punctuation">(</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># "张亚飞"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>可表示原始二进制（图片、文件等信息）</p>
</li>
</ul>
</li>
</ul>
<p>file 对象使用 open 函数来创建，下表列出了 file 对象常用的函数：</p>
<table>
<thead>
<tr>
<th align="left">号</th>
<th align="left">方法及描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left"><code>file.close(</code>)关闭文件。关闭后文件不能再进行读写操作。</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left"><code>file.flush()</code>刷新文件内部缓冲，直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left"><code>file.fileno()</code>返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。</td>
</tr>
<tr>
<td align="left">4</td>
<td align="left"><code>file.isatty()</code>如果文件连接到一个终端设备返回 True，否则返回 False。</td>
</tr>
<tr>
<td align="left">6</td>
<td align="left"><code>file.read([size]))</code>从文件读取指定的字节数，如果未给定或为负则读取所有。</td>
</tr>
<tr>
<td align="left">7</td>
<td align="left"><code>file.readline([size])</code>读取整行，包括 “\n” 字符。</td>
</tr>
<tr>
<td align="left">8</td>
<td align="left"><code>file.readlines([sizeint])</code>读取所有行并返回列表，若给定sizeint&gt;0，返回总和大约为sizeint字节的行, 实际读取值可能比 <code>sizeint</code> 较大, 因为需要填充缓冲区。</td>
</tr>
<tr>
<td align="left">9</td>
<td align="left"><code>file.seek(offset[, whence)</code>移动文件读取指针到指定位置</td>
</tr>
<tr>
<td align="left">10</td>
<td align="left"><code>file.tell()</code>返回文件当前位置。</td>
</tr>
<tr>
<td align="left">11</td>
<td align="left"><code>file.truncate([size])</code>从文件的首行首字符开始截断，截断文件为 size 个字符，无 size 表示从当前位置截断；截断之后后面的所有字符被删除，其中 windows 系统下的换行代表2个字符大小。</td>
</tr>
<tr>
<td align="left">12</td>
<td align="left"><code>file.write(str)</code>将字符串写入文件，返回的是写入的字符长度。</td>
</tr>
<tr>
<td align="left">13</td>
<td align="left"><code>file.writelines(sequence)</code>向文件写入一个序列字符串列表，如果需要换行则要自己加入每行的换行符。</td>
</tr>
</tbody></table>
<h3 id="一、打开文件"><a href="#一、打开文件" class="headerlink" title="一、打开文件"></a>一、打开文件</h3><p>了解了文件系统，我们可以非常方便的通过文件来读写数据；我们在使用文件之前要先将文件打开，在Python中要实现文件操作是非常简单的。我们可以使用Python内置的<code>open</code>函数来打开文件，open函数语法如下：</p>
<pre class="line-numbers language-python"><code class="language-python">open<span class="token punctuation">(</span>file<span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> buffering<span class="token operator">=</span>None<span class="token punctuation">,</span> encoding<span class="token operator">=</span>None<span class="token punctuation">,</span> errors<span class="token operator">=</span>None<span class="token punctuation">,</span> newline<span class="token operator">=</span>None<span class="token punctuation">,</span> closefd<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>open函数中的参数有很多，这里介绍5个常用参数：</p>
<ul>
<li><p>file参数<br>file参数用于表示要打开的文件， 可以是字符串或整数。 如果file是字符串， 则表示文件名， 文件名既可以是当前目录的相对路径， 也可以是绝对路径； 如果file是整数， 则表示一个已经打开的文件 。</p>
</li>
<li><p>mode参数</p>
<p>mode参数用于设置文件操作模式， 用字符串表示， 这里所说的操作模式是指要打开什么样的文件（字符文件或二进制文件）以及做什么样的操作（读、写或追加），具体如下表所示。</p>
<table>
<thead>
<tr>
<th align="left">模式</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">t</td>
<td align="left">文本模式 (默认)。</td>
</tr>
<tr>
<td align="left">x</td>
<td align="left">写模式，新建一个文件，如果该文件已存在则会报错。</td>
</tr>
<tr>
<td align="left">b</td>
<td align="left">二进制模式。</td>
</tr>
<tr>
<td align="left">+</td>
<td align="left">打开一个文件进行更新(可读可写)。</td>
</tr>
<tr>
<td align="left">U</td>
<td align="left">通用换行模式（不推荐）。</td>
</tr>
<tr>
<td align="left">r</td>
<td align="left">以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。</td>
</tr>
<tr>
<td align="left">rb</td>
<td align="left">以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。</td>
</tr>
<tr>
<td align="left">r+</td>
<td align="left">打开一个文件用于读写。文件指针将会放在文件的开头。</td>
</tr>
<tr>
<td align="left">rb+</td>
<td align="left">以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。</td>
</tr>
<tr>
<td align="left">w</td>
<td align="left">打开一个文件只用于写入。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。</td>
</tr>
<tr>
<td align="left">wb</td>
<td align="left">以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。一般用于非文本文件如图片等。</td>
</tr>
<tr>
<td align="left">w+</td>
<td align="left">打开一个文件用于读写。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。</td>
</tr>
<tr>
<td align="left">wb+</td>
<td align="left">以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件，并从开头开始编辑，即原有内容会被删除。如果该文件不存在，创建新文件。一般用于非文本文件如图片等。</td>
</tr>
<tr>
<td align="left">a</td>
<td align="left">打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。也就是说，新的内容将会被写入到已有内容之后。如果该文件不存在，创建新文件进行写入。</td>
</tr>
<tr>
<td align="left">ab</td>
<td align="left">以二进制格式打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。也就是说，新的内容将会被写入到已有内容之后。如果该文件不存在，创建新文件进行写入。</td>
</tr>
<tr>
<td align="left">a+</td>
<td align="left">打开一个文件用于读写。如果该文件已存在，文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在，创建新文件用于读写。</td>
</tr>
<tr>
<td align="left">ab+</td>
<td align="left">以二进制格式打开一个文件用于追加。如果该文件已存在，文件指针将会放在文件的结尾。如果该文件不存在，创建新文件用于读写。</td>
</tr>
</tbody></table>
<p>下图展示了如何根据程序的需要来设置<code>open</code>函数的操作模式。</p>
<p><img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/file-open-mode.png" alt="文件操作模式"></p>
<table>
<thead>
<tr>
<th align="center">模式</th>
<th align="center">r</th>
<th align="center">r+</th>
<th align="center">w</th>
<th align="center">w+</th>
<th align="center">a</th>
<th align="center">a+</th>
</tr>
</thead>
<tbody><tr>
<td align="center">读</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center"></td>
<td align="center">+</td>
<td align="center"></td>
<td align="center">+</td>
</tr>
<tr>
<td align="center">写</td>
<td align="center"></td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
</tr>
<tr>
<td align="center">创建</td>
<td align="center"></td>
<td align="center"></td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
</tr>
<tr>
<td align="center">覆盖</td>
<td align="center"></td>
<td align="center"></td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">指针在开始</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center">+</td>
<td align="center"></td>
<td align="center"></td>
</tr>
<tr>
<td align="center">指针在结尾</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
</tbody></table>
<ul>
<li><p><code>r+</code>、<code>rt+</code>、<code>rb+</code>，默认光标位置：起始位置</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 文件内容：床前明月光</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r+'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 读取内容</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 床前明月光</span>

<span class="token comment" spellcheck="true"># 写入内容</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"你好呀"</span><span class="token punctuation">)</span>

file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 文件内容为 床前明月光你好呀</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 文件内容：床前明月光</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r+'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 写入内容</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"李白"</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 李白明月光</span>

<span class="token comment" spellcheck="true"># 读取内容</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 明月光</span>

file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>  <span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p><code>w+</code>、<code>wt+</code>、<code>wb+</code>，默认光标位置：起始位置（清空文件）</p>
<p><code>w+</code>如果先写入，会将原内容抹去（这其实和w一样），再读的时候要注意加个<code>f.seek()</code>。<strong>如果先读取，会读取不到内容（因为用的是w+,会先抹去文件里面的内容），直接就写入了。</strong></p>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'wt+'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 读取内容 清空</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 写入内容</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"你好呀"</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 将光标位置重置起始</span>
file_object<span class="token punctuation">.</span>seek<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 读取内容</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 你好呀</span>

file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p><code>x+</code>、<code>xt+</code>、<code>xb+</code>，默认光标位置：起始位置（新文件）</p>
</li>
<li><p><code>a+</code>、<code>at+</code>、<code>ab+</code>，默认光标位置：末尾</p>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'at+'</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 写入内容</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"张亚飞"</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 将光标位置重置起始</span>
file_object<span class="token punctuation">.</span>seek<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 读取内容</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 床前明月光张亚飞</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
</li>
<li><p>buffering：</p>
<p>设置缓冲。文件io操作的缓冲行为分为：<strong>全缓冲：</strong>同系统及磁盘块大小有关，n个字节后执行一次写入操作。<strong>行缓冲：</strong>遇到换行符执行一次写操作。<strong>无缓冲：</strong>立刻执行写操作。buffering默认为-1，系统默认的全缓冲，buffering可以设置为大于1的任意整数，字节数为buffering的全缓冲，buffering=1，设置为行缓冲模式，buffering=0， 设置为无缓冲模式。</p>
</li>
<li><p>encoding参数</p>
<p>encoding用来指定打开文件时的文件编码， 默认是UTF-8编码， 主要用于打开文本文件。如果需要指定字符编码，可以传入encoding参数，如果不指定，默认值是None，那么在读取文件时使用的是操作系统默认的编码。需要提醒大家，如果不能保证保存文件时使用的编码方式与encoding参数指定的编码方式是一致的，那么就可能因无法解码字符而导致读取文件失败。</p>
</li>
<li><p>errors参数</p>
<p>errors参数用来指定在文本文件发生编码错误时如何处理。 推荐errors参数的取值为’ignore’， 表示在遇到编码错误时忽略该错误， 程序会继续执行， 不会退出。  </p>
</li>
</ul>
<p>在使用<code>open</code>函数时，如果打开的文件是字符文件（文本文件），可以通过<code>encoding</code>参数来指定读写文件使用的字符编码。没有指定该参数，则使用系统默认的编码作为读写文件的编码。</p>
<p>使用示例：</p>
<ul>
<li><p>读取文本文件</p>
<p>info.txt</p>
<pre class="line-numbers language-python"><code class="language-python">床前明月光
疑是地上霜<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>代码</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 1.打开文件</span>
<span class="token comment" spellcheck="true">#    - 路径：</span>
<span class="token comment" spellcheck="true">#        相对路径：'info.txt'</span>
<span class="token comment" spellcheck="true">#        绝对路径：'G:/学习/Python学习/Python基础/code/chapter20/info.txt'</span>
<span class="token comment" spellcheck="true">#     - 模式</span>
<span class="token comment" spellcheck="true">#         rb，表示读取文件原始的二进制（r, 读 read；b, 二进制 binary；）</span>
<span class="token comment" spellcheck="true"># 1.打开文件</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 2.读取文件内容，并赋值给data</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># b'\xe5\xba\x8a\xe5\x89\x8d\xe6\x98\x8e\xe6\x9c\x88\xe5\x85\x89\r\n\xe7\x96\x91\xe6\x98\xaf\xe5\x9c\xb0\xe4\xb8\x8a\xe9\x9c\x9c'</span>
text <span class="token operator">=</span> data<span class="token punctuation">.</span>decode<span class="token punctuation">(</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>text<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 床前明月光</span>
<span class="token comment" spellcheck="true"># 疑是地上霜</span>

<span class="token comment" spellcheck="true"># 3.关闭文件</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 2.读取文件内容，并赋值给data</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> 
<span class="token comment" spellcheck="true"># 床前明月光</span>
<span class="token comment" spellcheck="true"># 疑是地上霜</span>
<span class="token comment" spellcheck="true"># 3.关闭文件</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>读取图片等非文本内容文件</p>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'图片.jpg'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00...'</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<p><strong>注意事项</strong>：</p>
<ul>
<li><p>路径</p>
<ul>
<li><p>相对路径：相对与某个基准目录的路径，默认基准目录位于运行代码所在路径。</p>
<p>例如，file_example.py和图片.jpg在同一目录下，那么file_example.py中读取图片.jpg的相对路径可以写成</p>
<pre><code> G:\学习\Python学习\Python基础\code\chapter20 的目录

2020/12/23  16:39    &lt;DIR&gt;          .
2020/12/23  16:39    &lt;DIR&gt;          ..
2020/12/23  16:39             1,332 file_example1.py
2020/12/23  16:31                32 info.txt
2020/12/23  16:38            99,579 图片.jpg
               3 个文件        100,943 字节
               2 个目录 574,338,805,760 可用字节

G:\学习\Python学习\Python基础\code\chapter20&gt;python file_example1.py</code></pre>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'图片.jpg'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</li>
<li><p>绝对路径：绝对路径是指文件在硬盘上存储的完整路径。</p>
<p>上例中的绝对路径为</p>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'G:/学习/Python学习/Python基础/code/chapter20/图片.jpg'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>
data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00...'</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
</li>
<li><p>读文件时，文件不存在程序会报错。</p>
<pre class="line-numbers language-python"><code class="language-python">Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
  File <span class="token string">"G:/学习/Python学习/Python基础/code/chapter20/file_example1.py"</span><span class="token punctuation">,</span> line <span class="token number">36</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator">&lt;</span>module<span class="token operator">></span>
    file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'图片1.jpg'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>
FileNotFoundError<span class="token punctuation">:</span> <span class="token punctuation">[</span>Errno <span class="token number">2</span><span class="token punctuation">]</span> No such file <span class="token operator">or</span> directory<span class="token punctuation">:</span> <span class="token string">'图片1.jpg'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 判断路径是否存在？</span>
<span class="token keyword">import</span> os

file_path <span class="token operator">=</span> <span class="token string">"G:\学习\Python学习\Python基础\code\chapter20\info.txt"</span>
exists <span class="token operator">=</span> os<span class="token punctuation">.</span>path<span class="token punctuation">.</span>exists<span class="token punctuation">(</span>file_path<span class="token punctuation">)</span>
<span class="token keyword">if</span> exists<span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 1.打开文件</span>
    file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 2.读取文件内容，并赋值给data</span>
    data <span class="token operator">=</span> file_object<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 3.关闭文件</span>
    file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span>
<span class="token keyword">else</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"文件不存在"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<h3 id="二、关闭文件"><a href="#二、关闭文件" class="headerlink" title="二、关闭文件"></a>二、关闭文件</h3><p>在打开文件后， 如果不再使用该文件， 则应该将其关闭， 会用到close（） 方法。  </p>
<ul>
<li><p>在finally代码块中关闭文件<br>对文件的操作往往会抛出异常， 为了保证对文件的操作无论是正常结束还异常结束， 都能够关闭文件， 我们应该将对close（） 方法的调用放在异常处理的finally代码块中。  </p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">try</span><span class="token punctuation">:</span>
    f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'data.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'文件打开成功'</span><span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>file<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token keyword">except</span> FileNotFoundError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'文件不存在'</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> OSError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'处理OS异常'</span><span class="token punctuation">)</span>
<span class="token keyword">finally</span><span class="token punctuation">:</span>
    <span class="token keyword">if</span> f <span class="token keyword">is</span> <span class="token operator">not</span> None<span class="token punctuation">:</span>
        f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'文件关闭成功'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>在with as 代码块中关闭文件（<strong>上下文语法</strong>）</p>
<p>对于<code>open</code>函数返回的文件对象，还可以使用<code>with</code>上下文语法在文件操作完成后自动执行文件对象的<code>close</code>方法，这样可以让代码变得更加简单，因为不需要再写<code>finally</code>代码块来执行关闭文件释放资源的操作。需要提醒大家的是，并不是所有的对象都可以放在<code>with</code>上下文语法中，只有符合<strong>上下文管理器协议</strong>（有<code>__enter__</code>和<code>__exit__</code>魔术方法）的对象才能使用这种语法，Python标准库中的<code>contextlib</code>模块也提供了对<code>with</code>上下文语法的支持，后面再为大家进行讲解。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">try</span><span class="token punctuation">:</span>
    <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'data.txt'</span><span class="token punctuation">,</span> <span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> file<span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span>file<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> FileNotFoundError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'无法打开指定的文件!'</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> LookupError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'指定了未知的编码!'</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> UnicodeDecodeError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'读取文件时解码错误!'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>with as提供了一个代码块， 在as后面声明一个资源变量， 在with as代码块结束之后自动释放资源。  </p>
<p>在Python 2.7 后，with又支持同时对多个文件的上下文进行管理，即：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">"xxxx.txt"</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> f1<span class="token punctuation">,</span> open<span class="token punctuation">(</span><span class="token string">"xxxx.txt"</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> f2<span class="token punctuation">:</span>
    <span class="token keyword">pass</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
</li>
</ul>
<h3 id="三、读写文本文件"><a href="#三、读写文本文件" class="headerlink" title="三、读写文本文件"></a>三、读写文本文件</h3><ul>
<li><code>read(size)</code>：从文件中读取字符串， size限制读取的字符数， 默认size=-1，指对读取所有内容。  </li>
<li><code>readline(size)</code>：在读取到换行符或文件尾时返回单行字符串。 如果已经到文件尾， 则返回一个空字符串。 size是限制读取的字符数， size=-1表示没有限制。  </li>
<li><code>readlines()</code>: 读取文件数据到一个字符串列表中， 每一行数据都是列表的一个元素。  </li>
<li><code>write(s)</code>：将字符串s写入文件中， 并返回写入的字符数。  </li>
<li><code>writelines(lines)</code>： 向文件中写入一个字符串列表。 不添加行分隔符， 因此通常为每一行末尾都提供行分隔符  </li>
<li><code>flush()</code>：刷新写缓冲区， 在文件没有关闭的情况下将数据写入文件中。</li>
</ul>
<p><strong>示例</strong></p>
<ul>
<li><p>read()， 读</p>
<ul>
<li><p>读所有【常用】</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span>encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
data <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>
data <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>读n个字符（字节）【会用到】</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># 文件内容 张亚飞</span>
f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 读1个字符</span>
data <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 张</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span>encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 读1个字符</span>
chunk1 <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
chunk2 <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>chunk1<span class="token punctuation">,</span>chunk2<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 张 亚飞</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 读1个字节</span>
data <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">,</span> type<span class="token punctuation">(</span>data<span class="token punctuation">)</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># b'\xe5\xba\x8a' &lt;class 'bytes'></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 读1个字节</span>
chunk1 <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
chunk2 <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
chunk3 <span class="token operator">=</span> f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>chunk1<span class="token punctuation">,</span>chunk2<span class="token punctuation">,</span>chunk3<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># b'\xe5\xba\x8a' b'\xe5\x89\x8d' b'\xe6'</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
</li>
<li><p><code>readline()</code>方法</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

v1 <span class="token operator">=</span> f<span class="token punctuation">.</span>readline<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>v1<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 床前明月光\n</span>

v2 <span class="token operator">=</span> f<span class="token punctuation">.</span>readline<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>v2<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 疑是地上霜\n</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
v1 <span class="token operator">=</span> f<span class="token punctuation">.</span>readline<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>v1<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 床前明月光\n</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>

f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
v2 <span class="token operator">=</span> f<span class="token punctuation">.</span>readline<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>v2<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 床前明月光\n</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<ul>
<li><p><code>readlines()</code>，读所有行，每行作为列表的一个元素</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
data_list <span class="token operator">=</span> f<span class="token punctuation">.</span>readlines<span class="token punctuation">(</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data_list<span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># ['床前明月光\n', '疑是地上霜']</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>for in循环，读大文件（readline加强版）【常见】</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token keyword">for</span> line <span class="token keyword">in</span> f<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>line<span class="token punctuation">.</span>strip<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 床前明月光</span>
<span class="token comment" spellcheck="true"># 疑是地上霜</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<ul>
<li><p>write 写入</p>
<p>如果要向文件中写入内容，可以在打开文件时使用<code>w</code>或者<code>a</code>作为操作模式，前者会截断之前的文本内容写入新的内容，后者是在原来内容的尾部追加新的内容。</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">,</span>encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"张亚飞"</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'ab'</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>write<span class="token punctuation">(</span> <span class="token string">"张亚飞"</span><span class="token punctuation">.</span>encode<span class="token punctuation">(</span><span class="token string">"utf-8"</span><span class="token punctuation">)</span> <span class="token punctuation">)</span>
f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>flush，刷到硬盘</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">,</span>encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 不是写到了硬盘，而是写在缓冲区，系统会将缓冲区的内容刷到硬盘。</span>
    f<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"张亚飞"</span><span class="token punctuation">)</span>
    f<span class="token punctuation">.</span>flush<span class="token punctuation">(</span><span class="token punctuation">)</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'files/account.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'a'</span><span class="token punctuation">)</span>

<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    user <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"用户名："</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> user<span class="token punctuation">.</span>upper<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token string">"Q"</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>
    pwd <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"密码："</span><span class="token punctuation">)</span>
    data <span class="token operator">=</span> <span class="token string">"{}-{}\n"</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span>
    file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span>data<span class="token punctuation">)</span>
    file_object<span class="token punctuation">.</span>flush<span class="token punctuation">(</span><span class="token punctuation">)</span>

file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>移动光标位置（字节）</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r+'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 移动到指定字节的位置</span>
f<span class="token punctuation">.</span>seek<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>
f<span class="token punctuation">.</span>write<span class="token punctuation">(</span><span class="token string">"张亚飞"</span><span class="token punctuation">)</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>注意：在a模式下，调用write在文件中写入内容时，永远只能将内容写入到尾部，不会写到光标的位置。</p>
</li>
<li><p>获取当前光标位置</p>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>

p1 <span class="token operator">=</span> f<span class="token punctuation">.</span>tell<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>p1<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 0</span>

f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 读3个字符 3*3=9字节</span>

p2 <span class="token operator">=</span> f<span class="token punctuation">.</span>tell<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>p2<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 9</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-python"><code class="language-python">f <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'info.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'rb'</span><span class="token punctuation">)</span>

p1 <span class="token operator">=</span> f<span class="token punctuation">.</span>tell<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>p1<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 0</span>

f<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 读3个字节</span>

p2 <span class="token operator">=</span> f<span class="token punctuation">.</span>tell<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>p2<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 3</span>

f<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<p><strong>基础案例</strong></p>
<ul>
<li><p>案例1：复制一个文件到另一个文件中</p>
<p>将原始文件<code>src_file.txt</code>中的内容写入到文件<code>dest.txt</code>中。注意，<code>src_file.txt</code>以<code>gbk</code>方式编码，要求用<code>utf-8</code>写入。</p>
<pre class="line-numbers language-python"><code class="language-python">Beautiful <span class="token keyword">is</span> better than ugly<span class="token punctuation">.</span>
Explicit <span class="token keyword">is</span> better than implicit<span class="token punctuation">.</span>
Simple <span class="token keyword">is</span> better than complex<span class="token punctuation">.</span>
Complex <span class="token keyword">is</span> better than complicated<span class="token punctuation">.</span>
Flat <span class="token keyword">is</span> better than nested<span class="token punctuation">.</span>
Sparse <span class="token keyword">is</span> better than dense<span class="token punctuation">.</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>示例代码：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'src_file.ttx'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'r'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'gbk'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> f1<span class="token punctuation">:</span>
    content <span class="token operator">=</span> f1<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'dest_file.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'w'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> f2<span class="token punctuation">:</span>
        f2<span class="token punctuation">.</span>write<span class="token punctuation">(</span>content<span class="token punctuation">)</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'文件复制成功'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>案例2：用户注册，获取用户输入用户名和密码，将其写入到文件中</p>
<pre class="line-numbers language-python"><code class="language-python">user <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"请输入用户名："</span><span class="token punctuation">)</span>
pwd <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"请输入密码："</span><span class="token punctuation">)</span>
data <span class="token operator">=</span> <span class="token string">"{}-{}"</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">"files/info.txt"</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'wt'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span>data<span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>案例3：多用户注册</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true"># w写入文件，先清空文件；再在文件中写入内容。</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">"files/info.txt"</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'wt'</span><span class="token punctuation">,</span> encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    user <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"请输入用户名："</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> user<span class="token punctuation">.</span>upper<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token string">"Q"</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>
    pwd <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"请输入密码："</span><span class="token punctuation">)</span>
    data <span class="token operator">=</span> <span class="token string">"{}-{}\n"</span><span class="token punctuation">.</span>format<span class="token punctuation">(</span>user<span class="token punctuation">,</span> pwd<span class="token punctuation">)</span>

    file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span>data<span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<h3 id="四、读写二进制文件"><a href="#四、读写二进制文件" class="headerlink" title="四、读写二进制文件"></a>四、读写二进制文件</h3><p>读写二进制文件跟读写文本文件的操作类似，但是需要注意，在使用<code>open</code>函数打开文件时，如果要进行读操作，操作模式是<code>'rb'</code>，如果要进行写操作，操作模式是<code>'wb'</code>。还有一点，读写文本文件时，<code>read</code>方法的返回值以及<code>write</code>方法的参数是<code>str</code>对象（字符串），而读写二进制文件时，<code>read</code>方法的返回值以及<code>write</code>方法的参数是<code>bytes-like</code>对象（字节串）。下面的代码实现了将当前路径下名为<code>guido.jpg</code>的图片文件复制到<code>吉多.jpg</code>文件中的操作。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">try</span><span class="token punctuation">:</span>
    <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'1.jpg'</span><span class="token punctuation">,</span> <span class="token string">'rb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> file1<span class="token punctuation">:</span>
        data <span class="token operator">=</span> file1<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'2.jpg'</span><span class="token punctuation">,</span> <span class="token string">'wb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> file2<span class="token punctuation">:</span>
        file2<span class="token punctuation">.</span>write<span class="token punctuation">(</span>data<span class="token punctuation">)</span>
<span class="token keyword">except</span> FileNotFoundError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'指定的文件无法打开.'</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> IOError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'读写文件时出现错误.'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'程序执行结束.'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果要复制的图片文件很大，一次将文件内容直接读入内存中可能会造成非常大的内存开销，为了减少对内存的占用，可以为<code>read</code>方法传入<code>size</code>参数来指定每次读取的字节数，通过循环读取和写入的方式来完成上面的操作，代码如下所示。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">try</span><span class="token punctuation">:</span>
    <span class="token keyword">with</span> open<span class="token punctuation">(</span><span class="token string">'1.jpg'</span><span class="token punctuation">,</span> <span class="token string">'rb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> file1<span class="token punctuation">,</span> \
        open<span class="token punctuation">(</span><span class="token string">'2.jpg'</span><span class="token punctuation">,</span> <span class="token string">'wb'</span><span class="token punctuation">)</span> <span class="token keyword">as</span> file2<span class="token punctuation">:</span>
        data <span class="token operator">=</span> file1<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">512</span><span class="token punctuation">)</span>
        <span class="token keyword">while</span> data<span class="token punctuation">:</span>
            file2<span class="token punctuation">.</span>write<span class="token punctuation">(</span>data<span class="token punctuation">)</span>
            data <span class="token operator">=</span> file1<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">512</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> FileNotFoundError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'指定的文件无法打开.'</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> IOError<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'读写文件时出现错误.'</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'程序执行结束.'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><strong>小高级案例</strong>：超前</p>
<p>利用Python想某个网址发送请求并获取结果（利用第三方的模块）</p>
<ul>
<li><p>下载第三方模块<code>requests</code></p>
<pre class="line-numbers language-python"><code class="language-python">pip install requests<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</li>
<li><p>使用</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> requests

res <span class="token operator">=</span> requests<span class="token punctuation">.</span>get<span class="token punctuation">(</span>url<span class="token operator">=</span><span class="token string">"网址"</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>案例1：去网上下载一点文本，文本信息写入文件。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> requests

res <span class="token operator">=</span> requests<span class="token punctuation">.</span>get<span class="token punctuation">(</span>url<span class="token operator">=</span><span class="token string">"https://movie.douban.com/j/search_subjects?type=movie&amp;tag=%E7%83%AD%E9%97%A8&amp;sort=recommend&amp;page_limit=20&amp;page_start=20"</span><span class="token punctuation">,</span>
    headers<span class="token operator">=</span><span class="token punctuation">{</span><span class="token string">"User-Agent"</span><span class="token punctuation">:</span> <span class="token string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"</span><span class="token punctuation">}</span>
<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 网络传输的原始二进制信息（bytes）</span>
<span class="token comment" spellcheck="true"># res.content</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'movie.txt'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'wb'</span><span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span>res<span class="token punctuation">.</span>content<span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>案例2：去网上下载一张图片，图片写入本地文件。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> requests

res <span class="token operator">=</span> requests<span class="token punctuation">.</span>get<span class="token punctuation">(</span>url<span class="token operator">=</span><span class="token string">"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1031041206,3898962502&amp;fm=26&amp;gp=0.jpg"</span><span class="token punctuation">,</span>headers<span class="token operator">=</span><span class="token punctuation">{</span><span class="token string">"User-Agent"</span><span class="token punctuation">:</span> <span class="token string">"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"</span><span class="token punctuation">}</span>
<span class="token punctuation">)</span>
<span class="token comment" spellcheck="true"># 网络传输的原始二进制信息（bytes）</span>
<span class="token comment" spellcheck="true"># res.content</span>
file_object <span class="token operator">=</span> open<span class="token punctuation">(</span><span class="token string">'img1.png'</span><span class="token punctuation">,</span> mode<span class="token operator">=</span><span class="token string">'wb'</span><span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>write<span class="token punctuation">(</span>res<span class="token punctuation">.</span>content<span class="token punctuation">)</span>
file_object<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<p>注意事项：</p>
<ul>
<li>路径<ul>
<li>绝对路径</li>
<li>相对路径</li>
</ul>
</li>
<li>文件不存在时，w模式会新建然后再写入内容；文件存在时，w模式会清空文件再写入内容。</li>
</ul>
<h3 id="五、文件和文件夹操作"><a href="#五、文件和文件夹操作" class="headerlink" title="五、文件和文件夹操作"></a>五、文件和文件夹操作</h3><p>除了文件读写之外，关于文件的其他操纵可以通过<code>os</code>模块。</p>
<h4 id="1-文件删除"><a href="#1-文件删除" class="headerlink" title="1. 文件删除"></a>1. 文件删除</h4><p>语法：你可以用<code>remove()</code>方法删除文件，需要提供要删除的文件名作为参数。</p>
<pre class="line-numbers language-python"><code class="language-python">os<span class="token punctuation">.</span>remove<span class="token punctuation">(</span>file_name<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>示例：下例将删除一个已经存在的文件test2.txt。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> os
<span class="token comment" spellcheck="true"># 删除一个已经存在的文件test2.txt</span>
os<span class="token punctuation">.</span>remove<span class="token punctuation">(</span><span class="token string">"test2.txt"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="2-文件重命名"><a href="#2-文件重命名" class="headerlink" title="2. 文件重命名"></a>2. 文件重命名</h4><p>语法：rename()方法需要两个参数，当前的文件名和新文件名。</p>
<pre class="line-numbers language-py"><code class="language-py">os.rename(current_file_name, new_file_name)<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>例子：下例将重命名一个已经存在的文件test1.txt。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> os
<span class="token comment" spellcheck="true"># 重命名文件test1.txt到test2.txt。</span>
os<span class="token punctuation">.</span>rename<span class="token punctuation">(</span> <span class="token string">"test1.txt"</span><span class="token punctuation">,</span> <span class="token string">"test2.txt"</span> <span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="3-创建和删除文件夹"><a href="#3-创建和删除文件夹" class="headerlink" title="3. 创建和删除文件夹"></a>3. 创建和删除文件夹</h4><ul>
<li><p>创建文件夹</p>
<p>语法：可以使用os模块的mkdir()方法在当前目录下创建新的目录们。你需要提供一个包含了要创建的目录名称的参数。</p>
<pre class="line-numbers language-python"><code class="language-python">os<span class="token punctuation">.</span>mkdir<span class="token punctuation">(</span>newdir<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>示例：下例将在当前目录下创建一个新目录test。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> os
<span class="token comment" spellcheck="true"># 创建目录test</span>
os<span class="token punctuation">.</span>mkdir<span class="token punctuation">(</span><span class="token string">"test"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>删除文件夹</p>
<p>语法：<code>rmdir()</code>方法删除目录，目录名称以参数传递,在删除这个目录之前，它的所有内容应该先被清除。</p>
<pre class="line-numbers language-python"><code class="language-python">os<span class="token punctuation">.</span>rmdir<span class="token punctuation">(</span><span class="token string">'dirname'</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>示例：以下是删除” /tmp/test”目录的例子。目录的完全合规的名称必须被给出，否则会在当前目录下搜索该目录。</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token keyword">import</span> os
<span class="token comment" spellcheck="true"># 删除”/tmp/test”目录</span>
os<span class="token punctuation">.</span>rmdir<span class="token punctuation">(</span> <span class="token string">"/tmp/test"</span>  <span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
</ul>
<h4 id="4-获取和切换目录"><a href="#4-获取和切换目录" class="headerlink" title="4. 获取和切换目录"></a>4. 获取和切换目录</h4><ul>
<li>获取当前目录</li>
</ul>
<pre class="line-numbers language-python"><code class="language-python">os<span class="token punctuation">.</span>getcwd<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ul>
<li>切换指定目录<br>语法：可以用chdir()方法来改变当前的目录。chdir()方法需要的一个参数是你想设成当前目录的目录名称。<pre class="line-numbers language-python"><code class="language-python">os<span class="token punctuation">.</span>chdir<span class="token punctuation">(</span><span class="token string">"newdir"</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</li>
</ul>
<h4 id="5-获取当前目录下所有文件列表"><a href="#5-获取当前目录下所有文件列表" class="headerlink" title="5. 获取当前目录下所有文件列表"></a>5. 获取当前目录下所有文件列表</h4><p>  语法：获取当前目录下所有文件列表有两种实现方法。</p>
<pre class="line-numbers language-python"><code class="language-python">os<span class="token punctuation">.</span>listdir<span class="token punctuation">(</span>dir<span class="token punctuation">)</span>
os<span class="token punctuation">.</span>walk<span class="token punctuation">(</span>top<span class="token punctuation">,</span> topdown<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">,</span> onerror<span class="token operator">=</span>None<span class="token punctuation">,</span> followlinks<span class="token operator">=</span><span class="token boolean">False</span><span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">></span> Directory tree generator<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h4 id="6-文件备份"><a href="#6-文件备份" class="headerlink" title="6. 文件备份"></a>6. 文件备份</h4><p><strong>要求</strong>：用户输入需要备份的文件名，对文件进行备份，备份文件名为原文件名后加[复件],后缀不变。如test.txt的备份文件为test[复件].txt。</p>
<p><strong>代码实现</strong>：</p>
<pre class="line-numbers language-python"><code class="language-python"><span class="token comment" spellcheck="true">#1.获取文件名</span>
old_file_name <span class="token operator">=</span> input<span class="token punctuation">(</span><span class="token string">"请输入要备份的文件名(需要后缀):"</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">#2。打开这个文件（"r")</span>
f_read <span class="token operator">=</span> open<span class="token punctuation">(</span>old_file_name<span class="token punctuation">,</span><span class="token string">"r"</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">#new_file_name = old_file_name+"[复件]"</span>
position <span class="token operator">=</span> old_file_name<span class="token punctuation">.</span>rfind<span class="token punctuation">(</span><span class="token string">"."</span><span class="token punctuation">)</span>
new_file_name <span class="token operator">=</span> old_file_name<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">:</span>position<span class="token punctuation">]</span><span class="token operator">+</span><span class="token string">"[复件]"</span><span class="token operator">+</span>old_file_name<span class="token punctuation">[</span>position<span class="token punctuation">:</span><span class="token punctuation">]</span>

<span class="token comment" spellcheck="true">#3.创建一个文件，xxx[复件].txt</span>
f_write <span class="token operator">=</span> open<span class="token punctuation">(</span>new_file_name<span class="token punctuation">,</span><span class="token string">"w"</span><span class="token punctuation">)</span>


<span class="token comment" spellcheck="true">#4.往源文件中读取内容,写入备份的文件中</span>
<span class="token comment" spellcheck="true">#content = f_read.read()</span>
<span class="token comment" spellcheck="true">#f_write.write(content)</span>
<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    content <span class="token operator">=</span> f_read<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">)</span>

    <span class="token keyword">if</span> len<span class="token punctuation">(</span>content<span class="token punctuation">)</span><span class="token operator">==</span><span class="token number">0</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>
    f_write<span class="token punctuation">.</span>write<span class="token punctuation">(</span>content<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">#5.关闭两个文件</span>
f_read<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
f_write<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="练习：批量文件重命名"><a href="#练习：批量文件重命名" class="headerlink" title="练习：批量文件重命名"></a>练习：批量文件重命名</h4><p>要求：提示用户输入重命名的文件夹名称，对文件夹中所有文件进行重命名，并写入到新文件夹，新文件夹的名称为原始文件夹名后加<code>[备份]</code>，。命名规则为在原名之前加<code>[飞凡空间]-</code>，如原始文件名为<code>图片.png</code>，新名为<code>[飞凡空间]-图片.png</code>。</p>
<h3 id="六、巩固提升"><a href="#六、巩固提升" class="headerlink" title="六、巩固提升"></a>六、巩固提升</h3><ol>
<li><p>日志分析，计算某用户<code>223.73.89.192</code>访问次数。日志文件如下：<code>access.log</code></p>
<pre><code>49.89.167.91 - - [17/Dec/2020:03:43:50 +0800] "GET /wiki/detail/3/40 HTTP/1.1" 301 0 "-" "Mozilla/5.0(Linux;Android 5.1.1;OPPO A33 Build/LMY47V;wv) AppleWebKit/537.36(KHTML,link Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36 LieBaoFast/4.51.3" "-"
49.89.167.91 - - [17/Dec/2020:03:44:11 +0800] "GET /wiki/detail/3/40/ HTTP/1.1" 200 8033 "-" "Mozilla/5.0(Linux;Android 5.1.1;OPPO A33 Build/LMY47V;wv) AppleWebKit/537.36(KHTML,link Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36 LieBaoFast/4.51.3" "-"
203.208.60.66 - - [17/Dec/2020:03:47:58 +0800] "GET /media/uploads/2019/11/17/pic/s1.png HTTP/1.1" 200 710728 "-" "Googlebot-Image/1.0" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /wiki/detail/3/40/ HTTP/1.1" 200 8033 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/stark/plugins/font-awesome/css/font-awesome.css HTTP/1.1" 200 37414 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/stark/plugins/bootstrap/css/bootstrap.css HTTP/1.1" 200 146010 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/web/css/commons.css HTTP/1.1" 200 3674 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/mdeditor/editormd/css/editormd.preview.css HTTP/1.1" 200 60230 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/stark/js/jquery-3.3.1.min.js HTTP/1.1" 200 86927 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/stark/plugins/bootstrap/js/bootstrap.min.js HTTP/1.1" 200 37045 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:26 +0800] "GET /static/mdeditor/editormd/lib/marked.min.js HTTP/1.1" 200 19608 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:27 +0800] "GET /static/mdeditor/editormd/lib/prettify.min.js HTTP/1.1" 200 17973 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:27 +0800] "GET /static/mdeditor/editormd/fonts/fontawesome-webfont.woff2?v=4.3.0 HTTP/1.1" 200 56780 "https://pythonav.com/static/mdeditor/editormd/css/editormd.preview.css" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:27 +0800] "GET /static/mdeditor/editormd/editormd.js HTTP/1.1" 200 163262 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:28 +0800] "GET /static/mdeditor/mdeditor-preview-init.js HTTP/1.1" 200 261 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:29 +0800] "GET /static/stark/plugins/font-awesome/fonts/fontawesome-webfont.woff2?v=4.7.0 HTTP/1.1" 200 77160 "https://pythonav.com/static/stark/plugins/font-awesome/css/font-awesome.css" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"
223.73.89.192 - - [17/Dec/2020:03:48:29 +0800] "GET /media/uploads/2019/02/22/Gobook/_book/ssl2.png HTTP/1.1" 200 203535 "https://pythonav.com/wiki/detail/3/40/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" "-"</code></pre>
</li>
<li><p>日志分析升级，计算所有用户的访问次数。</p>
</li>
<li><p>筛选出股票 当前价大于 20 的所有股票数据。</p>
<pre><code>股票代码,股票名称,当前价,涨跌额,涨跌幅,年初至今,成交量,成交额,换手率,市盈率(TTM),股息率,市值
SH601778,N晶科,6.29,+1.92,+43.94%,+43.94%,259.66万,1625.52万,0.44%,22.32,-,173.95亿
SH688566,吉贝尔,52.66,+6.96,+15.23%,+122.29%,1626.58万,8.09亿,42.29%,89.34,-,98.44亿
SH688268,华特气体,88.80,+11.72,+15.20%,+102.51%,622.60万,5.13亿,22.87%,150.47,-,106.56亿
SH600734,实达集团,2.60,+0.24,+10.17%,-61.71%,1340.27万,3391.14万,2.58%,亏损,0.00%,16.18亿
SH900957,凌云B股,0.36,+0.033,+10.09%,-35.25%,119.15万,42.10万,0.65%,44.65,0.00%,1.26亿
SZ000584,哈工智能,6.01,+0.55,+10.07%,-4.15%,2610.86万,1.53亿,4.36%,199.33,0.26%,36.86亿
SH600599,熊猫金控,6.78,+0.62,+10.06%,-35.55%,599.64万,3900.23万,3.61%,亏损,0.00%,11.25亿
SH600520,文一科技,8.21,+0.75,+10.05%,-24.05%,552.34万,4464.69万,3.49%,亏损,0.00%,13.01亿
SH603682,锦和商业,11.73,+1.07,+10.04%,+48.29%,2746.63万,3.15亿,29.06%,29.62,-,55.42亿
SZ300831,派瑞股份,12.27,+1.12,+10.04%,+208.29%,25.38万,311.41万,0.32%,60.59,-,39.26亿</code></pre>
</li>
<li><p>实现名片管理系统文件版。</p>
<p><strong>要求</strong>：功能包含添加、删除、修改、查询一个名片，查询所有名片，保存信息、退出系统功能。每次运行系统从文件中加载名片数据，用户选择保存信息将信息写入文件。</p>
</li>
</ol>
<h3 id="简单的总结"><a href="#简单的总结" class="headerlink" title="简单的总结"></a>简单的总结</h3><p>通过读写文件的操作，我们可以实现数据持久化。在Python中可以通过<code>open</code>函数来获得文件对象，可以通过文件对象的<code>read</code>和<code>write</code>方法实现文件读写操作。如果要对文件或文件夹进行创建、删除等操作，可以通过<code>os</code>模块来实现，当然，<code>os</code>模块的功能还有很多，之后我们还会再介绍。学了文件相关操作之后，我们的技能库又丰富了一些。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io" rel="external nofollow noreferrer">张亚飞</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io/python/base/di-20-pian-wen-jian-cao-zuo/">https://zhangyafeii.gitee.io/python/base/di-20-pian-wen-jian-cao-zuo/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                                    <span class="chip bg-color">Python之路</span>
                                </a>
                            
                                <a href="/tags/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/">
                                    <span class="chip bg-color">文件操作</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b9bf0e29501275f4f23c',
        clientSecret: '1c56bc88fdb7b23ee3712916a38e5e8d1311823a',
        repo: 'github.io',
        owner: 'zhangyafeii',
        admin: "zhangyafeii",
        id: '2020-12-21T08-00-01',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/python/base/di-21-pian-wen-jian-cao-zuo-kuo-zhan-pian/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/21.jpg" class="responsive-img" alt="第21篇：文件操作扩展">
                        
                        <span class="card-title">第21篇：文件操作扩展</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            学习目标：了解常见的csv、excel、ini文件的相关操作，熟悉文件压缩的方法，掌握路径相关的概念和操作。不要求记住每一种文件的具体操作方法，但要做好笔记，以备将来查阅。
一、CSV文件1. CSV文件介绍CSV（Comma Separa
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-12-22
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Python/" class="post-category">
                                    Python
                                </a>
                            
                            <a href="/categories/Python/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Python之路</span>
                    </a>
                    
                    <a href="/tags/%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C/">
                        <span class="chip bg-color">文件操作</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/python/base/di-19-pian-yi-chang-chu-li/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Python%E6%96%87%E6%A1%A3/assets/%E7%AC%AC19%E7%AF%87.jpg" class="responsive-img" alt="第19篇：异常处理">
                        
                        <span class="card-title">第19篇：异常处理</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            学习目标：了解Python异常处理的常用知识，掌握异常处理的基本用法。
为增强程序的健壮性， 我们也需要考虑异常处理方面的内容。 例如， 在读取文件时需要考虑文件不存在、 文件格式不正确等异常情况。 这就是本节要介绍的异常处理。  
一、第
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-12-20
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Python/" class="post-category">
                                    Python
                                </a>
                            
                            <a href="/categories/Python/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Python%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Python之路</span>
                    </a>
                    
                    <a href="/tags/%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/">
                        <span class="chip bg-color">异常处理</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 飞凡空间<br />'
            + '文章作者: 张亚飞<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">344.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "12";
                    var startDate = "18";
                    var startHour = "12";
                    var startMinute = "12";
                    var startSecond = "12";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-google-plus"></i>
    </a>



    <a href="mailto:zhangyafeii@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1271570224" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1271570224" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/js/cursor.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
